from flask import Flask, current_app, g, request, session

app = Flask(__name__)

# 设置一个密钥用于会话
app.secret_key = 'your_secret_key'

# 在应用上下文中存储全局变量
@app.before_request
def before_request():
    g.db_connection = "Database Connection"

# 在请求上下文中访问请求参数
@app.route('/')
def home():
    # 访问应用上下文
    app_name = current_app.name
    db_connection = g.db_connection

    # 访问请求上下文
    user_agent = request.headers.get('User-Agent')

    # 访问会话
    session['username'] = 'Alice'

    return (f'App Name: {app_name}\n'
            f'DB Connection: {db_connection}\n'
            f'User Agent: {user_agent}\n'
            f'Session Username: {session.get("username")}')

# 在请求上下文中访问会话数据
@app.route('/profile')
def profile():
    username = session.get('username', 'Guest')
    return f'Welcome, {username}!'

if __name__ == '__main__':
    app.run(debug=True)